import { ICheckUserToken, IUserLogin } from '@/api/login.typings'
import { ref } from 'vue'
import { http } from './http'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL

const getTokenFromStorage = (): string => {
  return uni.getStorageSync('token') || ''
}

const token = ref(getTokenFromStorage())

/** 设置新 token */
export const setToken = (newToken: string) => {
  token.value = newToken
  uni.setStorageSync('token', newToken)
}

/** 清除 token */
export const clearToken = () => {
  token.value = ''
  uni.removeStorageSync('token')
}

export const getCurrentUserId = () => {
  return uni.getStorageSync('userInfo').id
}

/** 获取响应式 token */
export const useToken = () => {
  return token
}

/** 获取带 headers 的请求头对象（可选） */
export const useAuthHeaders = (): Record<string, string> => {
  return {
    'x-auth-token': `Bearer ${token.value}`,
    'x-auth-platform': 'WX',
  }
}
/**
 *
 * @returns 检查token是否有效
 */
export const checkTokenIsValid = async () => {
  // 登录检查
  const token = uni.getStorageSync('token')
  let tokenIsValid = false
  if (!token) {
    return tokenIsValid
  }
  const checkTokenDTO: ICheckUserToken = {
    token: `Bearer ${token}`,
    platform: 'WX',
  }
  // console.log('checkTokenDTO', checkTokenDTO)
  // 去后端检查token是否有效
  const res = await http.post<IUserLogin>(
    `${API_BASE_URL}/api/v1/user/check_token_status`,
    checkTokenDTO,
  )
  tokenIsValid = res.code === 200
  return tokenIsValid
}
